import Taro from "@tarojs/taro";
import {
  ADD_WORK,
  DELET_WORK,
  SHOW_ADD_WORK_MODAL,
  HIDE_ADD_WORK_MODAL,
  GET_WORKS
} from "../constants/workToDo";
import { serverDomain, port } from "../config/config";

export function onShowAddWorkModal() {
  return {
    type: SHOW_ADD_WORK_MODAL
  };
}

export function onHideWorkModal() {
  return {
    type: HIDE_ADD_WORK_MODAL
  };
}

export function onAddWork(data, cb) {
  return dispatch => {
    Taro.showToast({
      title: "添加待办事项...",
      icon: "loading",
      mask: true
    }).then(() => {
      Taro.request({
        url: `${serverDomain}:${port}/work/addWork`,
        method: "POST",
        data: data,
        success: res => {
          if (res.data.code === 0) {
            dispatch({
              type: ADD_WORK
            });
            cb && cb();
          } else {
            Taro.atMessage({
              message: "服务器出错",
              type: "error",
              duration:3000
            });
            dispatch({
              type: HIDE_ADD_WORK_MODAL
            });
          }
        },
        fail: () => {
          Taro.atMessage({
            message: "服务器出错",
            type: "error",
            duration:3000
          });
          dispatch({
            type: HIDE_ADD_WORK_MODAL
          });
        },
        complete: Taro.hideToast
      });
    });
  };
}

export function onGetWorks(user, cb) {
  return dispatch => {
    Taro.showToast({
      title: "获取待办事项...",
      icon: "loading",
      mask: true
    }).then(() => {
      Taro.request({
        url: `${serverDomain}:${port}/work/getWorks`,
        method: "GET",
        data: { user },
        success: res => {
          if (res.data.code === 0) {
            dispatch({
              type: GET_WORKS,
              payload:res.data.data
            });
            cb && cb();
          } else
            Taro.atMessage({
              message: "服务器出错",
              type: "error",
              duration:3000
            });
        },
        fail: () => {
          Taro.atMessage({
            message: "服务器出错",
            type: "error",
            duration:3000
          });
        },
        complete: Taro.hideToast
      });
    });
  };
}

export function onDeleteWork() {}

